package com.demo.demo.rabbitmq.work;

import com.demo.demo.utils.RabbitMQUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Customer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("work",true,false,false,null);
        channel.basicQos(1);
        /**
         * 关闭消息自动确认 true为开启  false 为关闭
         * 优点：每次只拿一条消息，并且不会自动确认，自动确认的话，如果rabbitmq发送过来一条消息，消费者会自动确认然后标记消息删除
         * 如果此时消费者宕机或者进程阻塞就会造成消息丢失
         * 每次拿一条消息是为了实现能者多劳
         */
        channel.basicConsume("work",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(10);
                    System.out.println("消费者1：" + new String(body));
                    //参数一：消息的标志 参数二：是否一次确认多条消息
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}
